import axios from 'axios'
import config from '@/config'
import { message } from 'antd'

const request = {
  create() {
    const http = axios.create({
      baseURL: config.api,
      // timeout: 2500,
      // headers: {
      //   'X-System-Code': MENU_CODE.ISPACE,
      // },
    })
    http.interceptors.request.use(
      (config) => {
        if (config.method == 'post') {
          // 数据序列化成表单
          // const formData = new FormData()
          // Object.keys(config.data).forEach((key) => formData.append(key, config.data[key]))
          // config.data = formData
        }

        return config
      },
      (error) => {
        return Promise.reject(error)
      }
    )
    http.interceptors.response.use(
      (res) => {
        // const config = res?.config
        // const key = `${config?.method}-${config?.baseURL}${config?.url}`

        // 请求是下载文件的，直接返回
        if (res.config?.responseType === 'arraybuffer' && res.data) return res.data

        const responseData = res.data
        if (!responseData) {
          return Promise.reject(responseData)
        }
        return res.data
      },
      (error) => {
        error?.message && message.error(error?.message)
        return Promise.reject(error)
      }
    )

    return http
  },
}

export default request
